package org.hlopik.riverGuide.dao;

import com.google.appengine.repackaged.com.google.common.collect.Lists;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import org.hlopik.riverGuide.shared.RiverGuide;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jdo.PersistenceManagerFactoryUtils;
import org.springframework.stereotype.Repository;

/**
 *
 * @author f
 */
@Repository
public class RiverGuideDaoImpl implements RiverGuideDao {

    @Autowired
    private PersistenceManagerFactory persistenceManagerFactory;

    public void addRiverGuide(final RiverGuide riverGuide) {
        getPersistenceManager().makePersistent(riverGuide);
    }

    public RiverGuide getRiverGuideById(String id) {
        final PersistenceManager pm = getPersistenceManager();
        final RiverGuide result = pm.getObjectById(RiverGuide.class, id);
        pm.close();
        return result;
    }

    public long getRiverGuideCount() {
        final Query query = getPersistenceManager().newQuery(RiverGuide.class);
        query.setResult("count(id)");
        final long result = (Long) query.execute();
        return result;
    }

    public List<RiverGuide> getAllRiverGuides() {
        final PersistenceManager pm = getPersistenceManager();
        final Query query = pm.newQuery(RiverGuide.class);
        final List<RiverGuide> result = (List<RiverGuide>) query.execute();
        result.size();
        pm.close();
        return result;
    }

    private PersistenceManager getPersistenceManager() {
        return PersistenceManagerFactoryUtils.getPersistenceManager(persistenceManagerFactory, true);
    }

    public void setPersistenceManagerFactory(PersistenceManagerFactory persistenceManagerFactory) {
        this.persistenceManagerFactory = persistenceManagerFactory;
    }
}
